<template>
  <div class="container">
    <div class="title">{{ title }}</div>
    <div class="formBox">
      <el-form ref="form" label-width="80px" :model="form" :rules="rules">
        <div class="title">入住人基本信息</div>
        <div class="inline">
          <el-form-item label="电子合同">
            <el-switch v-model="isWeb" />
          </el-form-item>
          <el-form-item v-if="isWeb" label="选择模板">
            <el-select v-model="model" disabled placeholder="请选择">
              <el-option label="系统模板" :value="1" />
            </el-select>
          </el-form-item>
        </div>
        <div
          v-for="(item, index) in form.customer_arr"
          :key="index"
          class="inline"
        >
          <el-form-item
            v-if="item.customer_type == 1"
            label="姓名"
            :prop="`customer_arr[${index}].customer_name`"
            :rules="rules.customer_name"
          >
            <el-input v-model="item.customer_name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item
            v-else
            label="同住人"
            :prop="`customer_arr[${index}].customer_name`"
            :rules="rules.customer_name"
          >
            <el-input v-model="item.customer_name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item
            label="联系方式"
            :prop="`customer_arr[${index}].customer_mobile`"
            :rules="rules.customer_mobile"
          >
            <el-input
              v-model="item.customer_mobile"
              placeholder="请输入手机号"
            />
          </el-form-item>
          <el-form-item
            label="证件号"
            :prop="`customer_arr[${index}].customer_idcard`"
            :rules="rules.customer_idcard"
          >
            <el-input
              v-model="item.customer_idcard"
              placeholder="请输入身份证号"
              @input="changeIdcard"
            />
          </el-form-item>
          <div
            v-if="item.customer_type == 2"
            class="deleteTogether"
            @click="deleteTogether(index)"
          >
            <vab-icon icon="delete-back-2-line" />
          </div>
        </div>

        <div class="inline">
          <el-form-item label="入住周期" prop="start_date">
            <el-date-picker
              v-model="form.start_date"
              format="yyyy-MM-dd"
              placeholder="请选择开始日期"
              type="date"
              value-format="yyyy-MM-dd"
              @change="changeStart"
            />
          </el-form-item>
          <span class="daterange">--</span>
          <el-form-item label-width="0" prop="end_date">
            <el-date-picker
              v-model="form.end_date"
              format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              placeholder="请选择结束日期"
              type="date"
              value-format="yyyy-MM-dd"
              @change="changeEnd"
            />
          </el-form-item>
          <el-radio-group
            v-model="setTime"
            :disabled="form.start_date == null"
            size="small"
            @input="makeTime"
          >
            <el-radio-button label="1月">1月</el-radio-button>
            <el-radio-button label="3月">3月</el-radio-button>
            <el-radio-button label="6月">6月</el-radio-button>
            <el-radio-button label="1年">1年</el-radio-button>
          </el-radio-group>
        </div>
        <div v-if="isWeb">
          <div class="inline">
            <el-form-item class="money" label="租金" prop="pay_money">
              <el-select
                v-model="form.pay_type"
                placeholder="请选择"
                @change="paywayChange"
              >
                <el-option label="月租金" value="month" />
                <el-option label="日租金" value="day" />
              </el-select>
              <el-input
                v-model="form.pay_money"
                placeholder="请输入租金"
                type="number"
                @input="setBen"
              />
            </el-form-item>
            <el-form-item label="押金" prop="rent_deposit">
              <el-input
                v-model="form.rent_deposit"
                placeholder="请输入押金"
                type="number"
                @input="changeBen"
              />
            </el-form-item>
            <el-form-item label="居住人数" prop="people_number">
              <el-input
                v-model="form.people_number"
                placeholder="请输入居住人数"
                type="number"
              />
            </el-form-item>
          </div>
          <div class="inline">
            <el-form-item label="面积" prop="rent_area">
              <el-input v-model="form.rent_area" placeholder="请输入面积" />
            </el-form-item>
            <el-form-item label="支付时间" prop="pay_days">
              <el-select v-model="form.pay_days" placeholder="请选择支付时间">
                <div v-if="form.pay_type == 'month'">
                  <el-option
                    v-for="item in monthway"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </div>
                <div v-else-if="form.pay_type == 'day'">
                  <el-option label="一次性" :value="0" />
                  <el-option
                    v-for="n in 31"
                    :key="n"
                    :label="'每' + n + '天'"
                    :value="n"
                  />
                </div>
              </el-select>
            </el-form-item>
            <el-form-item label="用途" prop="used_type">
              <el-select v-model="form.used_type" placeholder="请选择">
                <el-option label="居住" value="居住" />
                <el-option label="商业" value="商业" />
              </el-select>
            </el-form-item>
          </div>
          <div class="inline">
            <el-form-item>
              <el-button @click="addItem">
                <i
                  v-if="form.deviceOther == ''"
                  class="el-icon-circle-plus add"
                ></i>
                <i v-else class="el-icon-success has"></i>
                房间物品
              </el-button>
              <el-button @click="addRule">
                <i
                  v-if="form.contract_other == ''"
                  class="el-icon-circle-plus add"
                ></i>
                <i v-else class="el-icon-success has"></i>
                其他约定
              </el-button>
            </el-form-item>
          </div>
        </div>
        <div class="inline">
          <el-form-item>
            <el-button @click="addTogether">
              <i
                v-if="form.customer_arr.length < 2"
                class="el-icon-circle-plus add"
              ></i>
              <i v-else class="el-icon-success has"></i>
              添加同住人
            </el-button>
            <el-button @click="addDidBill">
              <i class="el-icon-circle-plus add"></i>
              添加记账
            </el-button>
            <el-button @click="addDoBill">
              <i class="el-icon-circle-plus add"></i>
              添加待收账单
            </el-button>
            <el-button @click="addEdit">
              <i
                v-if="form.rent_remark == ''"
                class="el-icon-circle-plus add"
              ></i>
              <i v-else class="el-icon-success has"></i>
              添加备注
            </el-button>
          </el-form-item>
        </div>
        <div class="sub">
          <el-button v-if="isWeb">合同预览</el-button>
          <el-button type="primary" @click="submit">完 成</el-button>
        </div>
      </el-form>
    </div>
    <div v-if="form.bill_arr.length > 0" class="payDetail">
      <div class="title">账单详情</div>
      <el-table :data="form.bill_arr">
        <el-table-column label="费用名称" prop="bill_title" />
        <el-table-column label="金额" prop="bill_money">
          <template #default="{ row }">
            <div
              v-if="row.bill_type == 'income'"
              v-html="'+' + Number(row.bill_money).toFixed(2) + '元'"
            ></div>
            <div
              v-else-if="row.bill_type == 'payed'"
              v-html="'-' + Number(row.bill_money).toFixed(2) + '元'"
            ></div>
          </template>
        </el-table-column>
        <el-table-column label="类别" prop="is_pay">
          <template #default="{ row }">
            <div v-if="row.is_pay == '0'">待收账单</div>
            <div v-else-if="row.is_pay == '1'">完成账单</div>
          </template>
        </el-table-column>
        <el-table-column label="收付款日" prop="bill_date" />
        <el-table-column
          align="center"
          label="操作"
          show-overflow-tooltip
          width="85"
        >
          <template #default="{ row }">
            <el-button type="text" @click="payDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      append-to-body
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
    >
      <el-input
        v-model="textarea"
        :maxlength="textLength"
        :placeholder="placeholder"
        rows="5"
        show-word-limit
        type="textarea"
      />
      <template #footer>
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="saveText">确 定</el-button>
      </template>
    </el-dialog>
    <add-together ref="addTogether" @fetch-data="getTogether" />
    <did-bill ref="didBill" @fetch-data="getDidBill" />
    <do-bill ref="doBill" @fetch-data="getDoBill" />
  </div>
</template>

<script>
  import { getHouse } from '@/api/room'
  import { addRent, deleteBook } from '@/api/rent'
  import { addContract } from '@/api/contract'
  import { parseTime } from '@/utils/index'
  import { isPhone, isIdCard } from '@/utils/validate'
  import { mapActions, mapGetters } from 'vuex'
  import { handleActivePath } from '@/utils/routes'
  import addTogether from './components/addTogether'
  import didBill from './components/didBill'
  import doBill from './components/doBill'
  import dayjs from 'dayjs'
  export default {
    name: 'CheckIn',
    components: { addTogether, didBill, doBill },
    data() {
      const validatePhone = (rule, value, callback) => {
        if (!isPhone(value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      }
      const validateIdCard = (rule, value, callback) => {
        if (value && !isIdCard(value)) {
          callback(new Error('请输入正确的身份证号'))
        } else {
          callback()
        }
      }
      return {
        id: '',
        title: '',
        isWeb: false,
        model: 1,
        dialogVisible: false,
        dialogType: 'edit',
        dialogTitle: '',
        textarea: '',
        placeholder: '',
        textLength: 150,
        setTime: '',
        form: {
          room_id: '',
          start_date: parseTime(new Date(), '{y}-{m}-{d}'),
          end_date: '',
          customer_arr: [
            {
              customer_type: 1,
              customer_name: '',
              customer_mobile: '',
              customer_idcard: '',
            },
          ],
          bill_arr: [],
          contract_sn: '',
          rent_remark: '',
          // 电子合同
          pay_type: 'month',
          pay_money: '',
          pay_days: 1,
          rent_area: '',
          rent_deposit: '',
          people_number: null,
          used_type: '居住',
          customer_id: null,
          rent_sn: '',
          contract_other: '',
          deviceOther: '',
        },
        rules: {
          customer_name: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
          ],
          customer_mobile: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator: validatePhone, trigger: 'blur' },
          ],
          customer_idcard: [{ validator: validateIdCard, trigger: 'change' }],
          start_date: [
            {
              required: true,
              message: '请选择开始日期',
              trigger: ['blur', 'change'],
            },
          ],
          end_date: [
            {
              required: true,
              message: '请选择结束日期',
              trigger: ['blur', 'change'],
            },
          ],
          pay_money: [
            { required: true, message: '请输入租金', trigger: 'blur' },
          ],
          rent_deposit: [
            { required: true, message: '请输入押金', trigger: 'blur' },
          ],
          people_number: [
            { required: true, message: '请输入居住人数', trigger: 'blur' },
          ],
          rent_area: [
            { required: true, message: '请输入面积', trigger: 'blur' },
          ],
          pay_days: [
            {
              required: true,
              message: '请输入支付时间',
              trigger: ['blur', 'change'],
            },
          ],
          used_type: [
            {
              required: true,
              message: '请选择用途',
              trigger: ['blur', 'change'],
            },
          ],
        },
        formSubmit: false,
        monthway: [
          {
            value: 1,
            label: '每1月',
          },
          {
            value: 2,
            label: '每2月',
          },
          {
            value: 3,
            label: '每3月',
          },
          {
            value: 4,
            label: '每4月',
          },
          {
            value: 6,
            label: '每6月',
          },
          {
            value: 12,
            label: '每1年',
          },
          {
            value: 0,
            label: '一次性',
          },
        ],
      }
    },
    computed: {
      ...mapGetters({
        routes: 'routes/routes',
        visitedRoutes: 'tabs/visitedRoutes',
        name: 'rent/customer_name',
        idcard: 'rent/customer_idcard',
        mobile: 'rent/customer_mobile',
        start: 'rent/start_date',
        end: 'rent/end_date',
        sn: 'rent/rent_sn',
      }),
      pickerOptions() {
        let startDateVal = this.form.start_date
        return {
          disabledDate(time) {
            return time.getTime() < new Date(startDateVal).getTime()
          },
        }
      },
    },
    mounted() {
      this.id = this.$route.query.id
      this.form.customer_arr[0].customer_name = this.name ? this.name : ''
      this.form.customer_arr[0].customer_idcard = this.idcard ? this.idcard : ''
      this.form.customer_arr[0].customer_mobile = this.mobile ? this.mobile : ''
      this.form.start_date = this.start
        ? this.start
        : parseTime(new Date(), '{y}-{m}-{d}')
      this.form.end_date = this.end ? this.end : ''
      this.getRoomDetail()
    },
    methods: {
      ...mapActions({
        delVisitedRoute: 'tabs/delVisitedRoute',
        customer_name: 'rent/setName',
        customer_idcard: 'rent/setIdcard',
        customer_mobile: 'rent/setMobile',
        start_date: 'rent/setStart',
        end_date: 'rent/setEnd',
        rent_sn: 'rent/setSn',
      }),
      async handleTabRemove(rawPath) {
        await this.delVisitedRoute(rawPath)
        if (this.isActive(rawPath)) this.toLastTab()
      },
      toLastTab() {
        const latestView = this.visitedRoutes.slice(-1)[0]
        if (latestView) this.$router.push(latestView)
        else this.$router.push('/')
      },
      isActive(path) {
        return path === handleActivePath(this.$route, true)
      },
      setBen(e) {
        this.form.rent_deposit = e
      },
      changeBen() {
        this.$forceUpdate()
      },
      changeIdcard(e) {
        if (e == '') {
          setTimeout(() => {
            this.$refs['form'].clearValidate()
          }, 200)
        }
      },
      addEdit() {
        this.dialogType = 'edit'
        this.dialogTitle = '备注'
        this.placeholder = '请填写备注信息'
        this.textLength = 150
        this.textarea = this.form.rent_remark
        this.dialogVisible = true
      },
      addItem() {
        this.dialogType = 'item'
        this.dialogTitle = '房间物品'
        this.placeholder = '请填写房间物品'
        this.textLength = 300
        this.textarea = this.form.deviceOther
        this.dialogVisible = true
      },
      addRule() {
        this.dialogType = 'rule'
        this.dialogTitle = '其他约定'
        this.placeholder = '请填写其他约定'
        this.textLength = 300
        this.textarea = this.form.contract_other
        this.dialogVisible = true
      },
      addTogether() {
        this.$refs['addTogether'].showEdit()
      },
      getTogether(e) {
        this.form.customer_arr.push(e)
      },
      deleteTogether(index) {
        this.form.customer_arr.splice(index, 1)
      },
      addDidBill() {
        this.$refs['didBill'].showEdit()
      },
      getDidBill(e) {
        this.form.bill_arr.push(e)
      },
      addDoBill() {
        this.$refs['doBill'].showEdit(this.form)
      },
      getDoBill(e) {
        var list = JSON.parse(e)
        this.form.bill_arr = [...this.form.bill_arr, ...list]
      },
      payDelete(row) {
        this.form.bill_arr.splice(this.form.bill_arr.indexOf(row), 1)
      },
      closeDialog() {
        this.dialogVisible = false
      },
      saveText() {
        if (this.dialogType == 'edit') {
          this.form.rent_remark = this.textarea
        } else if (this.dialogType == 'item') {
          this.form.deviceOther = this.textarea
        } else if (this.dialogType == 'rule') {
          this.form.contract_other = this.textarea
        }
        this.close()
      },
      changeStart() {
        this.setTime = ''
      },
      changeEnd() {
        this.setTime = ''
      },
      paywayChange(e) {
        if (e == 'month') {
          this.form.pay_days = 1
        } else if (e == 'day') {
          this.form.pay_days = 0
        }
      },
      makeTime(e) {
        if (e == '1月') {
          this.form.end_date = this.addMonth(1)
        } else if (e == '3月') {
          this.form.end_date = this.addMonth(3)
        } else if (e == '6月') {
          this.form.end_date = this.addMonth(6)
        } else if (e == '1年') {
          this.form.end_date = this.addMonth(12)
        }
      },
      submit() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            let subData = Object.assign({}, this.form)
            let dataOne = {
              room_id: this.id,
              start_date: subData.start_date,
              end_date: subData.end_date,
              rent_remark: subData.rent_remark,
              customer_list: JSON.stringify(subData.customer_arr),
              bill_list: JSON.stringify(subData.bill_arr),
            }
            if (this.sn != null) {
              // 取消预定
              await deleteBook({ rent_sn: this.sn })
            }
            if (!this.isWeb) {
              // 正常入住
              const { data } = await addRent(dataOne)
              if (data.is_success) {
                this.$baseMessage(
                  '办理成功',
                  'success',
                  'vab-hey-message-success'
                )
                this.formSubmit = true
                this.handleTabRemove(this.$route.path)
                this.$router.go(-1)
              }
            } else {
              // 电子合同
              let dataTwo = {
                room_id: this.id,
                pay_type: subData.pay_type,
                pay_money: subData.pay_money,
                pay_days: subData.pay_days,
                rent_area: subData.rent_area,
                rent_deposit: subData.rent_deposit,
                people_number: subData.people_number,
                used_type: subData.used_type,
                contract_other: subData.contract_other,
                deviceOther: subData.deviceOther,
              }
              const { data } = await addRent(dataOne)
              dataTwo.customer_id = data.rent_info.customer_id
              dataTwo.rent_sn = data.rent_info.rent_sn
              const rentData = await addContract(dataTwo)
              if (rentData.data.is_success) {
                this.$baseMessage(
                  '办理成功',
                  'success',
                  'vab-hey-message-success'
                )
                this.formSubmit = true
                this.handleTabRemove(this.$route.path)
                this.$router.go(-1)
              }
            }
          }
        })
      },
      async getRoomDetail() {
        const { data } = await getHouse({ room_id: this.id })
        var info = data.info
        if (info.room_type == '1') {
          this.title = info.community_name + info.room_no
        } else if (info.room_type == '2') {
          this.title = info.home_name + info.room_no
        } else if (info.room_type == '3') {
          this.title = info.building_name + info.room_no
        }
      },
      addMonth(num) {
        return dayjs(new Date(this.form.start_date))
          .add(num, 'M')
          .subtract(1, 'd')
          .format('YYYY-MM-DD')
      },
      deleteVuex() {
        this.customer_name(null)
        this.customer_idcard(null)
        this.customer_mobile(null)
        this.start_date(null)
        this.end_date(null)
        this.rent_sn(null)
      },
    },
    beforeRouteLeave(to, form, next) {
      let initForm = JSON.stringify(this.$options.data().form)
      let afterForm = JSON.stringify(this.form)
      if (initForm != afterForm && !this.formSubmit) {
        setTimeout(() => {
          this.$baseConfirm(
            '当前信息未保存，离开页面将会放弃所有修改数据',
            null,
            () => {
              this.deleteVuex()
              next()
            }
          )
        }, 200)
      } else {
        this.deleteVuex()
        next()
      }
    },
  }
</script>
<style lang="scss" scoped>
  .container {
    padding: 16px;
  }
  .title {
    margin: 15px 0;
    font-weight: bolder;
    color: rgba(0, 0, 0, 0.85);
    font-size: 16px;
  }
  .formBox {
    max-width: 1000px;
    background: #f5f7ff;
    padding: 16px;
    .inline {
      display: flex;
      flex-wrap: wrap;
      .el-form-item {
        display: inline-block;
        margin-right: 10px;
        vertical-align: top;
      }
      .el-button {
        height: 32px;
        .add {
          color: #1890ff;
        }
        .has {
          color: #1ecb6b;
        }
      }
      ::v-deep .el-date-editor .el-range-separator {
        width: 10%;
      }
      .el-select {
        width: 200px;
      }
      .el-input {
        width: 200px;
      }
      .money {
        .el-select {
          width: 90px;
        }
        .el-input {
          width: 110px;
        }
      }
      .daterange {
        line-height: 32px;
        margin-right: 10px;
      }
      .deleteTogether {
        width: 32px;
        height: 32px;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #999;
        cursor: pointer;
        &:hover {
          color: #f17a7a;
        }
      }
    }
    .sub {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  }
  .payDetail {
    max-width: 1000px;
  }
</style>
